package com.aos.iot.socket.common.parser;

import cn.hutool.core.util.StrUtil;
import com.aos.iot.socket.common.message.Message;
import com.aos.iot.socket.common.message.Message.Direction;
import com.aos.iot.protocol.hll.util.CodeUtil;

public interface Parser<M extends Message> {

    default M boxing(Direction direction, String payload){
        M message = encode(direction, payload);
        if(message == null) {
            return null;
        }
        message.setContext(payload);
        message.setDirection(direction);
        message.setProtocol(protocol());
        return confirm(message) ? message : null;
    }

    default String unboxing(M message) {
        String decode = decode(message);
        message.setContext(decode);
        return confirm(message) ? decode : "";
    }

    M encode(Direction direction, String payload);

    String decode(M message);

    boolean confirm(M message);

    String protocol();

    default Parser<M> parser() {
        return this;
    }

    default String sub(String content, int fromIndexInclude, int toIndexExclude, boolean isHigh, String defaultValue) {
        if(StrUtil.length(content) > fromIndexInclude && StrUtil.length(content) >= toIndexExclude) {
            String res = StrUtil.sub(content, fromIndexInclude, toIndexExclude);
            return isHigh ? CodeUtil.highRotation(res) : res;
        }
        return defaultValue;
    }
}
